import { CryptoJS } from '@ohos/crypto-js'
import { hex_md5 } from './md5'
import buffer from '@ohos.buffer';
import webSocket from '@ohos.net.webSocket';
import { BusinessError } from '@ohos.base';

let iatWS;
let resultText = "";
let resultTextTemp = "";
let countdownInterval;

/**
 * 获取websocket url
 * 该接口需要后端提供，这里为了方便前端处理
 */
function getWebSocketUrl() {
  // var url = "wss://rtasr.xfyun.cn/v1/ws";
  // var appId = '60a0105a';
  // var secretKey = '5321e910df634f85b9dee73390cee195';
  // var ts = Math.floor(new Date().getTime() / 1000);
  // var signa = hex_md5(appId + ts);
  // var signatureSha = CryptoJS.HmacSHA1(signa, secretKey);
  // let signature: string = CryptoJS.enc.Base64.stringify(signatureSha);
  // signature = encodeURIComponent(signature);
  // return `${url}?appid=${appId}&ts=${ts}&signa=${signature}`;
  return `wss://sis-ext.cn-north-4.myhuaweicloud.com/v1/eb3b351353b04f1ba55cc0ffc7124f20/rasr/continue-stream`
}


function renderResult(resultData) {
  let jsonData = JSON.parse(resultData);
  if (jsonData.action == "started") {
    // 握手成功
    console.log("握手成功");
  } else if (jsonData.action == "result") {
    const data = JSON.parse(jsonData.data)
    // 转写结果
    let resultTextTemp = ""
    data.cn.st.rt.forEach((j) => {
      j.ws.forEach((k) => {
        k.cw.forEach((l) => {
          resultTextTemp += l.w;
        });
      });
    });
    if (data.cn.st.type == 0) {
      // 【最终】识别结果：
      resultText += resultTextTemp;
      resultTextTemp = ""
    }

    console.log('识别内容',  resultText + resultTextTemp)
  } else if (jsonData.action == "error") {
    // 连接发生错误
    console.log("出错了:", jsonData);
  }
}

export function connectWebSocket(XSubjectToken, callback) {
  let defaultIpAddress = getWebSocketUrl()
  iatWS = webSocket.createWebSocket();
  iatWS.on('open', (err: BusinessError, value: Object) => {
    console.log("on open, status:" + JSON.stringify(value));
    // var params = {
    //   common: {
    //     app_id: '60a0105a',
    //   },
    //   business: {
    //     language: "zh_cn",
    //     domain: "iat",
    //     accent: "mandarin",
    //     vad_eos: 5000,
    //     dwa: "wpgs",
    //   },
    //   data: {
    //     status: 0,
    //     format: "audio/L16;rate=16000",
    //     encoding: "lame",
    //   },
    // };
    // iatWS.send(JSON.stringify(params));
    callback('open')
  });
  iatWS.on('message', (err: BusinessError, value: string) => {
    console.log("on message, message:" + value);
    // renderResult(value);
    // callback('message', value)
    // // 当收到服务器的`bye`消息时（此消息字段仅为示意，具体字段需要与服务器协商），主动断开连接
    // if (value === 'bye') {
    //   iatWS.close((err: BusinessError, value: boolean) => {
    //     if (!err) {
    //       console.log("Connection closed successfully");
    //     } else {
    //       console.log("Failed to close the connection. Err: " + JSON.stringify(err));
    //     }
    //   });
    // }
  });
  iatWS.on('close', (err: BusinessError, value: webSocket.CloseResult) => {
    // callback('close', value)
    // console.log("on close, code is " + value.code + ", reason is " + value.reason);
  });
  iatWS.on('error', (err: BusinessError) => {
    // callback('error')
    console.log("on error, error:" + JSON.stringify(err));
  });
  iatWS.connect(defaultIpAddress, {
    header: {
      'X-Auth-Token': XSubjectToken
    }
  }, (err: BusinessError, value: boolean) => {
    if (!err) {
      console.log("Connected successfully");
    } else {
      callback('error')
      console.log("Connection failed. Err:" + JSON.stringify(err));
    }
  });
  return iatWS
  // iatWS.onopen = (e) => {
  //   // // 开始录音
  //   // recorder.start({
  //   //   sampleRate: 16000,
  //   //   frameSize: 1280,
  //   // });
  // };
  // iatWS.onmessage = (e) => {
  //   renderResult(e.data);
  // };
  // iatWS.onerror = (e) => {
  //   console.error(e);
  //   // recorder.stop();
  //   changeBtnStatus("CLOSED");
  // };
  // iatWS.onclose = (e) => {
  //   // recorder.stop();
  //   changeBtnStatus("CLOSED");
  // };
}
// iatWS.send(new Int8Array(frameBuffer));

// recorder.onFrameRecorded = ({ isLastFrame, frameBuffer }) => {
//   if (iatWS.readyState === iatWS.OPEN) {
//
//     if (isLastFrame) {
//       iatWS.send('{"end": true}');
//       changeBtnStatus("CLOSING");
//     }
//   }
// };
// recorder.onStop = () => {
//   clearInterval(countdownInterval);
// };

// btnControl.onclick = function () {
//   if (btnStatus === "UNDEFINED" || btnStatus === "CLOSED") {
//     connectWebSocket();
//   } else if (btnStatus === "CONNECTING" || btnStatus === "OPEN") {
//     // 结束录音
//     recorder.stop();
//   }
// };

